# src/benchmark.py
import time, random, pathlib, json
from blockchain import Blockchain

# 生成一条随机配置
def rand_config(i):
    return f"""hostname Router{i:05d}
interface GigabitEthernet0/0
 ip address 10.{i//256}.{i%256}.1 255.255.255.0
!
interface Loopback0
 ip address 172.16.{i//256}.{i%256} 255.255.255.255
!
end"""

bc = Blockchain()
count = 100_000
batch = 1000           # 每 1000 条打印一次进度
times = []             # 每次 add_block 耗时

start = time.perf_counter()
for i in range(1, count + 1):
    t0 = time.perf_counter()
    bc.add_block(rand_config(i), device_id=f"Router{i:05d}", operator="auto")
    t1 = time.perf_counter()
    times.append(t1 - t0)
    if i % batch == 0:
        elapsed = time.perf_counter() - start
        print(f"{i:>6d}/{count}  平均延迟 {sum(times[-batch:])/batch*1000:.2f} ms  TPS ≈ {batch/(time.perf_counter()-t0):.2f}")
        start = time.perf_counter()

# 汇总结果
total_time = sum(times)
report = {
    "total_blocks": count,
    "total_time_s": round(total_time, 2),
    "avg_latency_ms": round(sum(times)/count*1000, 2),
    "peak_tps": round(batch/min(times[-batch:]), 2),
    "chain_size_bytes": len(json.dumps(bc.to_list()).encode())
}
out = pathlib.Path(__file__).parent.parent / "data" / "benchmark.json"
out.write_text(json.dumps(report, indent=2))
print("压测结果已保存到", out)